package com.itheima.stock.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.stock.pojo.vo.resp.R;
import com.itheima.stock.pojo.vo.resp.ResponseCode;
import com.itheima.stock.security.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//定义授权过滤器,本质就是过滤一切请求,获取请求投的token,然后进行校验
public class AuthenticationFilter extends OncePerRequestFilter {
    /**
     * 过滤执行方法
     * @param request
     * @param response
     * @param filterChain 过滤器链
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String tokenStr = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        //合法性判断
        if(StringUtils.isBlank(tokenStr)){
            //如果为空,则放行,但是此时安全上下文没有认证成功的权限,后续的过滤器如果得不到这个票据,会自动拒绝
            filterChain.doFilter(request,response);
            return;
        }
        //
        Claims claims = JwtTokenUtil.checkJWT(tokenStr);
        if(claims==null){
            //票据不合法,过滤器终止
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            request.setCharacterEncoding("utf-8");
            R<Object> error = R.error(ResponseCode.INVALID_TOKEN);
            response.getWriter().write(new ObjectMapper().writeValueAsString(error));
            return;
        }
        //2.3
        String username = JwtTokenUtil.getUsername(tokenStr);
        String roles = JwtTokenUtil.getUserRole(tokenStr);
        String stripStr = StringUtils.strip(roles, "[]");
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(stripStr);
        //2.4
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
        //3.
        //以线程为维度
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //4.放行请求,有了安全上下文,后续过滤器无需认证
        filterChain.doFilter(request,response);
    }
}
